package com.mycp.splashlib

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.gyf.immersionbar.ImmersionBar
import com.mycp.splashlib.PrivacyPolicyActivity.Companion.getHtmlContent
import com.mycp.splashlib.PrivacyPolicyActivity.Companion.setWebVIewImage
import kotlin.concurrent.thread

class CommonWebViewActivity : AppCompatActivity() {
    private var url = ""
    private var title = ""
    private lateinit var webView: WebView
    private lateinit var abTitle: TextView
    private lateinit var progressBar: ProgressBar
    private lateinit var back: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.privacy_activity_webview_layout)
        ImmersionBar.with(this).fitsSystemWindows(true)
            .autoStatusBarDarkModeEnable(true, 0.2f)
            .statusBarColor(android.R.color.white).init()
        webView = findViewById(R.id.webView)
        abTitle = findViewById(R.id.toolbar_title)
        progressBar = findViewById(R.id.progressBar)
        back = findViewById(R.id.back)

        back.setOnClickListener {
            finish()
        }

        url = intent.getStringExtra("url").toString()
        title = intent.getStringExtra("title").toString()
        abTitle.text = title
        setUpWebviewAndLoadByUrl()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        webView.stopLoading()
        webView.destroy()
        super.onDestroy()
    }

    @SuppressLint("JavascriptInterface", "SetJavaScriptEnabled")
    protected fun setUpWebviewAndLoadByUrl() {
        webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
        webView.settings.javaScriptCanOpenWindowsAutomatically = true
        webView.settings.allowFileAccess = true
        webView.settings.defaultTextEncodingName = "UTF-8"
        webView.settings.loadWithOverviewMode = true
        webView.settings.useWideViewPort = true
        webView.settings.javaScriptEnabled = true
        webView.settings.domStorageEnabled = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }

        webView.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                progressBar.visibility = View.GONE
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                progressBar.visibility = View.GONE
            }
        }

        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                progressBar.visibility = View.VISIBLE
                progressBar.progress = newProgress
            }

            override fun onJsAlert(
                view: WebView,
                url: String,
                message: String,
                result: JsResult
            ): Boolean {
                return super.onJsAlert(view, url, message, result)
            }

            override fun onReceivedTitle(view: WebView, titleWeb: String) {
                super.onReceivedTitle(view, titleWeb)
                if (TextUtils.isEmpty(title)) {
                    abTitle.text = titleWeb
                }
            }
        }

        if (url.endsWith(".txt")) {
            thread {
                val htmlString = getHtmlContent(url)
                Handler(mainLooper).post {
                    webView.loadDataWithBaseURL(
                        null,
                        htmlString,
                        "text/html",
                        "utf-8",
                        null
                    )
                }
            }
        } else {
            webView.loadUrl(url)
        }
    }

    companion object {
        fun intentStart(context: Context, title: String, url: String) {
            val intent = Intent(context, CommonWebViewActivity::class.java)
            intent.putExtra("title", title)
            intent.putExtra("url", url)
            context.startActivity(intent)
        }
    }

}